<?php

require_once 'db.inc.php';
require_once 'utilities.inc.php';
// zr readme.txt

function get_max_match_id(){
	$match_id_rez = sql_get("SELECT MAX(id) as max_id FROM Matches");
	$match_id = $match_id_rez[0]['max_id'];
	return $match_id;
	}	
	
function create_match(){
	$sql=sql_set("INSERT INTO Matches (players_cnt,last_player_id,status) VALUES ('','','0')");
	return get_max_match_id();	
	}
	
function get_players(){
	return sql_get("SELECT id, name FROM Players");
}


show_all_params();

/*	

$players = sql_get("SELECT * FROM Players");
myprint($players);

$match_id = '1';  /// čia mūsų matč'as

foreach($players as $player){
	$participant_in_match = sql_get("SELECT * FROM Participants WHERE match_id={$match_id} AND player_id={$player['id']}");
	if ( empty( $participant_in_match )){
		 $query = "INSERT INTO 'Participants' VALUES({$match_id},{$player['id']});";
		 sql_set($query);
		 //$db->exec($query);
	}
}


/// kitas žingsnis
$participants_in_match = sql_get("SELECT * FROM Participants WHERE match_id={$match_id}");
$players_count = count($participants_in_match);
sql_set("UPDATE Matches SET players_cnt = $players_count WHERE  `id` = {$match_id}");

*/

$match_action = get_parameter('match_action');

$participants_action = get_parameter('participants_action');

if ($participants_action == 'insert'){
	$match_id = get_parameter('match_id');
	foreach( get_parameter('players') as $player_id) {
	   sql_set("INSERT INTO Participants (match_id,player_id ) VALUES ($match_id, $player_id)");
	}
}

if ($participants_action == 'remove'){
	$match_id = get_parameter('match_id');
	foreach( get_parameter('players') as $player_id) {
	   sql_set("DELETE FROM Participants WHERE match_id = $match_id AND player_id=$player_id)");
	}
}


function print_matches(){
	$Print = '<br  />';
	$matches = sql_get ("SELECT `ID`FROM `matches`WHERE STATUS =0");
	echo "<hr /> Macu sarasas <br />";
	foreach ($matches as $match)
		{
			$Print .= "<input type='radio' name='match_id' value='${match['id']}' /> ".$match['id']." <br/>";
	
		} 
	return $Print;
	
}


if ($match_action == 'start') {
	$created_match_id = create_match();
}
	
$players_list = '';
foreach( get_players() as $player){
	//myprint($player); echo "<br />";
	$players_list .= "<input type='checkbox' name='players[]' value='${player['id']}' /> ${player['id']}. ${player['name']} <br />";
}
echo "Created new match $created_match_id ";
$matches_list = print_matches(); 
echo <<<END
<form action="${_SERVER['PHP_SELF']}" method="POST">
$matches_list
$players_list
<!--<input type="hidden" name="match_id" value="$created_match_id" />-->
<input type="submit" name="participants_action" value="insert" />
<input type="submit" name="participants_action" value="remove" />
</form>

END;


//get_matches();
?>


<form action="<?php echo $_SERVER['PHP_SELF'];  ?>"  method="POST">
Matches running: <?php echo get_max_match_id() ?> <br />
<input type="submit" name="match_action" value="start" />
</form>
